// 工厂大屏监控系统 JavaScript

// 模拟数据 - 多工厂多车间
const mockData = {
    // 工厂总览数据
    factories: [
        {
            id: 1,
            name: 'DH-6',
            status: 'normal',
            location: '制造基地',
            workshops: 6,
            runningWorkshops: 6,
            avgOEE: 89.5,
            avgCapacity: 92.3,
            totalOrders: 1250,
            completedOrders: 1180
        },
        {
            id: 2,
            name: 'DX-2',
            status: 'warning',
            location: '制造基地',
            workshops: 5,
            runningWorkshops: 4,
            avgOEE: 82.1,
            avgCapacity: 85.7,
            totalOrders: 980,
            completedOrders: 920
        },
        {
            id: 3,
            name: 'DX-3',
            status: 'error',
            location: '制造基地',
            workshops: 4,
            runningWorkshops: 2,
            avgOEE: 45.2,
            avgCapacity: 52.1,
            totalOrders: 850,
            completedOrders: 650
        },
        {
            id: 4,
            name: 'O3',
            status: 'normal',
            location: '制造基地',
            workshops: 2,
            runningWorkshops: 2,
            avgOEE: 91.2,
            avgCapacity: 94.8,
            totalOrders: 720,
            completedOrders: 680
        }
    ],
    
    // 车间详细数据
    workshops: {
        1: { // DH-6工厂的车间 (6个车间)
            'A车间': {
                orders: {
                    pending: 156,
                    shipped: 1234,
                    delayed: 23,
                    progress: [
                        { id: 'ORD-001', promised: 1000, actual: 850, dueDate: '2024-01-15', status: 'delayed' },
                        { id: 'ORD-002', promised: 500, actual: 500, dueDate: '2024-01-20', status: 'normal' },
                        { id: 'ORD-003', promised: 800, actual: 720, dueDate: '2024-01-18', status: 'delayed' },
                        { id: 'ORD-004', promised: 1200, actual: 1200, dueDate: '2024-01-25', status: 'normal' },
                        { id: 'ORD-005', promised: 600, actual: 600, dueDate: '2024-01-22', status: 'normal' }
                    ]
                },
                production: {
                    lines: [
                        { id: 'DH6-1', status: 'normal', oee: 92.5, capacity: 95.2 },
                        { id: 'DH6-2', status: 'normal', oee: 88.7, capacity: 91.8 },
                        { id: 'DH6-3', status: 'warning', oee: 75.3, capacity: 78.9 },
                        { id: 'DH6-4', status: 'normal', oee: 94.1, capacity: 96.5 },
                        { id: 'DH6-5', status: 'error', oee: 45.2, capacity: 52.1 },
                        { id: 'DH6-6', status: 'normal', oee: 89.6, capacity: 93.2 },
                        { id: 'DH6-7', status: 'warning', oee: 82.4, capacity: 85.7 },
                        { id: 'DH6-8', status: 'normal', oee: 91.3, capacity: 94.8 },
                        { id: 'DH6-9', status: 'normal', oee: 87.9, capacity: 90.3 },
                        { id: 'DH6-10', status: 'normal', oee: 93.7, capacity: 97.1 }
                    ],
                    capacityTrend: [92.3, 94.1, 91.8, 89.5, 93.2, 95.7, 92.8, 94.5, 91.3, 93.9]
                },
                quality: {
                    totalTested: 20000,
                    defectiveCount: 5,
                    yieldRate: 99.975,
                    defectTypes: [
                        { type: '表面划伤', count: 2, percentage: 40 },
                        { type: '功能异常', count: 1, percentage: 20 },
                        { type: '尺寸偏差', count: 1, percentage: 20 },
                        { type: '外观缺陷', count: 1, percentage: 20 }
                    ],
                    defectDetails: [
                        { id: 'DEF-001', type: '表面划伤', batch: 'B20240115-001', time: '2024-01-15 14:30' },
                        { id: 'DEF-002', type: '表面划伤', batch: 'B20240115-002', time: '2024-01-15 15:45' },
                        { id: 'DEF-003', type: '功能异常', batch: 'B20240115-003', time: '2024-01-15 16:20' },
                        { id: 'DEF-004', type: '尺寸偏差', batch: 'B20240115-004', time: '2024-01-15 17:10' },
                        { id: 'DEF-005', type: '外观缺陷', batch: 'B20240115-005', time: '2024-01-15 18:05' }
                    ]
                },
                events: [
                    { type: 'error', message: '#5线设备故障，维修中', time: '2024-01-15 18:30' },
                    { type: 'warning', message: '#3线物料短缺，已通知补货', time: '2024-01-15 17:45' },
                    { type: 'success', message: '#1线完成今日生产计划', time: '2024-01-15 17:20' },
                    { type: 'warning', message: '#7线OEE低于目标值', time: '2024-01-15 16:55' },
                    { type: 'error', message: '质量检测发现异常批次', time: '2024-01-15 16:30' },
                    { type: 'success', message: '订单ORD-002按时完成', time: '2024-01-15 15:45' }
                ]
            },
            'B车间': {
                orders: { pending: 89, shipped: 567, delayed: 12 },
                production: {
                    lines: [
                        { id: 'DH6-11', status: 'normal', oee: 90.1, capacity: 93.5 },
                        { id: 'DH6-12', status: 'normal', oee: 87.3, capacity: 90.2 },
                        { id: 'DH6-13', status: 'normal', oee: 92.8, capacity: 95.1 },
                        { id: 'DH6-14', status: 'warning', oee: 78.5, capacity: 82.3 },
                        { id: 'DH6-15', status: 'normal', oee: 89.7, capacity: 92.8 }
                    ],
                    capacityTrend: [90.1, 92.3, 89.8, 91.5, 93.2, 90.8, 92.1, 89.5, 91.8, 93.5]
                },
                quality: { totalTested: 15000, defectiveCount: 3, yieldRate: 99.98 },
                events: [
                    { type: 'success', message: 'B车间完成月度目标', time: '2024-01-15 18:00' },
                    { type: 'warning', message: '#4线需要维护', time: '2024-01-15 17:30' }
                ]
            },
            'C车间': {
                orders: { pending: 67, shipped: 423, delayed: 8 },
                production: {
                    lines: [
                        { id: 1, status: 'normal', oee: 88.9, capacity: 91.7 },
                        { id: 2, status: 'normal', oee: 91.2, capacity: 94.3 },
                        { id: 3, status: 'normal', oee: 86.5, capacity: 89.8 },
                        { id: 4, status: 'normal', oee: 93.1, capacity: 96.2 }
                    ],
                    capacityTrend: [88.9, 91.2, 86.5, 93.1, 89.7, 92.3, 87.8, 94.1, 90.2, 93.8]
                },
                quality: { totalTested: 12000, defectiveCount: 2, yieldRate: 99.983 },
                events: [
                    { type: 'success', message: 'C车间质量达标', time: '2024-01-15 18:15' }
                ]
            },
            'D车间': {
                orders: { pending: 45, shipped: 345, delayed: 5 },
                production: {
                    lines: [
                        { id: 1, status: 'normal', oee: 91.5, capacity: 94.2 },
                        { id: 2, status: 'normal', oee: 89.3, capacity: 92.1 },
                        { id: 3, status: 'warning', oee: 76.8, capacity: 80.5 }
                    ],
                    capacityTrend: [91.5, 89.3, 76.8, 92.8, 88.9, 91.2, 77.5, 93.1, 89.7, 92.3]
                },
                quality: { totalTested: 10000, defectiveCount: 1, yieldRate: 99.99 },
                events: [
                    { type: 'success', message: 'D车间运行正常', time: '2024-01-15 18:10' }
                ]
            },
            'E车间': {
                orders: { pending: 34, shipped: 278, delayed: 3 },
                production: {
                    lines: [
                        { id: 1, status: 'normal', oee: 93.2, capacity: 95.8 },
                        { id: 2, status: 'normal', oee: 87.6, capacity: 90.4 },
                        { id: 3, status: 'normal', oee: 90.8, capacity: 93.5 }
                    ],
                    capacityTrend: [93.2, 87.6, 90.8, 94.1, 88.9, 91.5, 92.3, 89.7, 90.2, 93.8]
                },
                quality: { totalTested: 8500, defectiveCount: 1, yieldRate: 99.988 },
                events: [
                    { type: 'success', message: 'E车间效率提升', time: '2024-01-15 18:05' }
                ]
            },
            'F车间': {
                orders: { pending: 28, shipped: 234, delayed: 2 },
                production: {
                    lines: [
                        { id: 1, status: 'normal', oee: 88.4, capacity: 91.2 },
                        { id: 2, status: 'normal', oee: 92.7, capacity: 95.3 }
                    ],
                    capacityTrend: [88.4, 92.7, 89.8, 93.1, 90.2, 92.5, 88.9, 93.8, 91.1, 94.2]
                },
                quality: { totalTested: 7000, defectiveCount: 0, yieldRate: 100.0 },
                events: [
                    { type: 'success', message: 'F车间零缺陷运行', time: '2024-01-15 18:00' }
                ]
            }
        },
        2: { // DX-2工厂的车间 (5个车间)
            'A车间': {
                orders: { pending: 123, shipped: 456, delayed: 15 },
                production: {
                    lines: [
                        { id: 'DX2-1', status: 'warning', oee: 75.2, capacity: 78.9 },
                        { id: 'DX2-2', status: 'normal', oee: 85.3, capacity: 88.7 },
                        { id: 'DX2-3', status: 'error', oee: 45.1, capacity: 52.3 },
                        { id: 'DX2-4', status: 'normal', oee: 88.9, capacity: 91.5 },
                        { id: 'DX2-5', status: 'warning', oee: 79.8, capacity: 83.2 }
                    ],
                    capacityTrend: [75.2, 85.3, 45.1, 88.9, 79.8, 82.1, 87.5, 46.2, 89.3, 81.7]
                },
                quality: { totalTested: 18000, defectiveCount: 8, yieldRate: 99.956 },
                events: [
                    { type: 'error', message: '#3线设备故障', time: '2024-01-15 18:45' },
                    { type: 'warning', message: '#1线效率偏低', time: '2024-01-15 17:20' }
                ]
            },
            'B车间': {
                orders: { pending: 98, shipped: 389, delayed: 12 },
                production: {
                    lines: [
                        { id: 'DX2-6', status: 'normal', oee: 87.3, capacity: 90.1 },
                        { id: 'DX2-7', status: 'normal', oee: 91.5, capacity: 94.2 },
                        { id: 'DX2-8', status: 'warning', oee: 78.9, capacity: 82.3 },
                        { id: 'DX2-9', status: 'normal', oee: 89.7, capacity: 92.8 }
                    ],
                    capacityTrend: [87.3, 91.5, 78.9, 89.7, 88.2, 92.1, 79.5, 90.3, 87.8, 93.2]
                },
                quality: { totalTested: 15000, defectiveCount: 4, yieldRate: 99.973 },
                events: [
                    { type: 'warning', message: '#3线需要维护', time: '2024-01-15 18:30' },
                    { type: 'success', message: 'B车间质量改善', time: '2024-01-15 17:45' }
                ]
            },
            'C车间': {
                orders: { pending: 76, shipped: 312, delayed: 8 },
                production: {
                    lines: [
                        { id: 1, status: 'normal', oee: 90.2, capacity: 93.1 },
                        { id: 2, status: 'normal', oee: 86.7, capacity: 89.5 },
                        { id: 3, status: 'normal', oee: 92.8, capacity: 95.3 }
                    ],
                    capacityTrend: [90.2, 86.7, 92.8, 91.5, 87.9, 93.2, 89.8, 92.1, 88.3, 94.5]
                },
                quality: { totalTested: 12000, defectiveCount: 2, yieldRate: 99.983 },
                events: [
                    { type: 'success', message: 'C车间运行稳定', time: '2024-01-15 18:15' }
                ]
            },
            'D车间': {
                orders: { pending: 54, shipped: 245, delayed: 6 },
                production: {
                    lines: [
                        { id: 1, status: 'normal', oee: 88.9, capacity: 91.7 },
                        { id: 2, status: 'warning', oee: 76.3, capacity: 79.8 },
                        { id: 3, status: 'normal', oee: 91.4, capacity: 94.1 }
                    ],
                    capacityTrend: [88.9, 76.3, 91.4, 89.2, 77.8, 92.1, 88.5, 78.9, 90.7, 93.2]
                },
                quality: { totalTested: 9500, defectiveCount: 3, yieldRate: 99.968 },
                events: [
                    { type: 'warning', message: '#2线效率偏低', time: '2024-01-15 18:00' }
                ]
            },
            'E车间': {
                orders: { pending: 42, shipped: 198, delayed: 4 },
                production: {
                    lines: [
                        { id: 1, status: 'normal', oee: 93.1, capacity: 95.8 },
                        { id: 2, status: 'normal', oee: 89.5, capacity: 92.3 }
                    ],
                    capacityTrend: [93.1, 89.5, 92.8, 90.2, 93.5, 89.8, 91.7, 90.5, 92.1, 94.2]
                },
                quality: { totalTested: 7500, defectiveCount: 1, yieldRate: 99.987 },
                events: [
                    { type: 'success', message: 'E车间高效运行', time: '2024-01-15 17:55' }
                ]
            }
        },
        3: { // DX-3工厂的车间 (4个车间)
            'A车间': {
                orders: { pending: 89, shipped: 345, delayed: 10 },
                production: {
                    lines: [
                        { id: 'DX3-1', status: 'error', oee: 45.2, capacity: 52.1 },
                        { id: 'DX3-2', status: 'error', oee: 38.7, capacity: 45.5 },
                        { id: 'DX3-3', status: 'warning', oee: 65.5, capacity: 72.2 },
                        { id: 'DX3-4', status: 'error', oee: 42.8, capacity: 48.1 }
                    ],
                    capacityTrend: [45.2, 38.7, 65.5, 42.8, 47.1, 43.3, 62.2, 45.5, 48.8, 51.7]
                },
                quality: { totalTested: 16000, defectiveCount: 15, yieldRate: 99.906 },
                events: [
                    { type: 'error', message: 'DX3-1线设备故障，停机维修', time: '2024-01-15 18:40' },
                    { type: 'error', message: 'DX3-2线严重异常，需要紧急处理', time: '2024-01-15 17:35' },
                    { type: 'error', message: 'DX3-4线停机，等待备件', time: '2024-01-15 16:20' }
                ]
            },
            'B车间': {
                orders: { pending: 67, shipped: 278, delayed: 7 },
                production: {
                    lines: [
                        { id: 'DX3-5', status: 'error', oee: 52.3, capacity: 58.1 },
                        { id: 'DX3-6', status: 'error', oee: 48.8, capacity: 55.5 },
                        { id: 'DX3-7', status: 'warning', oee: 68.5, capacity: 75.8 }
                    ],
                    capacityTrend: [52.3, 48.8, 68.5, 55.2, 51.7, 63.1, 58.9, 52.3, 59.6, 61.8]
                },
                quality: { totalTested: 13000, defectiveCount: 12, yieldRate: 99.908 },
                events: [
                    { type: 'error', message: 'DX3-5线设备故障，停机维修', time: '2024-01-15 18:25' },
                    { type: 'error', message: 'DX3-6线严重异常，需要紧急处理', time: '2024-01-15 17:15' }
                ]
            },
            'C车间': {
                orders: { pending: 45, shipped: 198, delayed: 5 },
                production: {
                    lines: [
                        { id: 1, status: 'normal', oee: 90.7, capacity: 93.4 },
                        { id: 2, status: 'normal', oee: 88.2, capacity: 91.1 },
                        { id: 3, status: 'normal', oee: 91.9, capacity: 94.6 }
                    ],
                    capacityTrend: [90.7, 88.2, 91.9, 89.8, 91.3, 88.9, 92.5, 90.1, 91.7, 93.2]
                },
                quality: { totalTested: 11000, defectiveCount: 1, yieldRate: 99.991 },
                events: [
                    { type: 'success', message: 'C车间质量卓越', time: '2024-01-15 18:10' }
                ]
            },
            'D车间': {
                orders: { pending: 34, shipped: 156, delayed: 3 },
                production: {
                    lines: [
                        { id: 1, status: 'normal', oee: 92.4, capacity: 95.1 },
                        { id: 2, status: 'normal', oee: 89.8, capacity: 92.7 },
                        { id: 3, status: 'normal', oee: 87.3, capacity: 90.2 }
                    ],
                    capacityTrend: [92.4, 89.8, 87.3, 91.5, 90.2, 88.7, 92.8, 89.5, 91.1, 93.4]
                },
                quality: { totalTested: 9000, defectiveCount: 0, yieldRate: 100.0 },
                events: [
                    { type: 'success', message: 'D车间零缺陷运行', time: '2024-01-15 17:50' }
                ]
            }
        },
        4: { // O3工厂的车间 (2个车间)
            'A车间': {
                orders: { pending: 23, shipped: 89, delayed: 2 },
                production: {
                    lines: [
                        { id: 'O3-1', status: 'normal', oee: 91.2, capacity: 94.8 },
                        { id: 'O3-2', status: 'normal', oee: 88.7, capacity: 91.5 },
                        { id: 'O3-3', status: 'normal', oee: 93.5, capacity: 96.2 }
                    ],
                    capacityTrend: [91.2, 88.7, 93.5, 92.8, 89.2, 94.1, 90.5, 92.8, 91.9, 93.3]
                },
                quality: { totalTested: 8000, defectiveCount: 2, yieldRate: 99.975 },
                events: [
                    { type: 'success', message: 'O3-1线运行稳定', time: '2024-01-15 18:50' },
                    { type: 'success', message: 'O3-2线效率优秀', time: '2024-01-15 17:40' },
                    { type: 'success', message: '质量检测全部通过', time: '2024-01-15 16:30' }
                ]
            },
            'B车间': {
                orders: { pending: 15, shipped: 67, delayed: 1 },
                production: {
                    lines: [
                        { id: 'O3-4', status: 'normal', oee: 89.7, capacity: 92.9 },
                        { id: 'O3-5', status: 'normal', oee: 87.3, capacity: 90.5 }
                    ],
                    capacityTrend: [89.7, 87.3, 90.1, 88.2, 89.9, 87.8, 90.5, 88.7, 89.3, 91.1]
                },
                quality: { totalTested: 5500, defectiveCount: 1, yieldRate: 99.982 },
                events: [
                    { type: 'success', message: 'O3-4线运行稳定', time: '2024-01-15 18:20' },
                    { type: 'success', message: 'O3-5线效率优秀', time: '2024-01-15 17:10' }
                ]
            }
        }
    },
    
    // 当前选中的工厂和车间
    currentFactory: 1,
    currentWorkshop: 'A车间'
};

// 全局变量用于存储动画状态
let chipAnimationData = {
    totalChips: 0,
    isAnimating: false,
    animationTimer: null
};

// 数字滚动动画函数
function animateNumber(element, startValue, endValue, duration = 1000) {
    if (!element) return;
    
    const startTime = Date.now();
    const difference = endValue - startValue;
    
    // 添加动画CSS类
    element.classList.add('changing');
    
    function updateNumber() {
        const elapsed = Date.now() - startTime;
        const progress = Math.min(elapsed / duration, 1);
        
        // 使用缓动函数让动画更自然
        const easeOutQuart = 1 - Math.pow(1 - progress, 4);
        const currentValue = Math.floor(startValue + (difference * easeOutQuart));
        
        element.textContent = currentValue.toLocaleString();
        
        if (progress < 1) {
            requestAnimationFrame(updateNumber);
        } else {
            // 动画完成后移除CSS类
            setTimeout(() => {
                element.classList.remove('changing');
            }, 300);
        }
    }
    
    updateNumber();
}

// 生产芯数增长动画
function startChipGrowthAnimation() {
    if (chipAnimationData.isAnimating) return;
    
    chipAnimationData.isAnimating = true;
    
    function updateChips() {
        // 随机增加1-2个芯数
        const increment = Math.floor(Math.random() * 2) + 1;
        
        // 更新首屏工厂卡片中的生产芯数
        updateFactoryCardsChips(increment);
        
        // 更新二级页面的生产芯数（如果当前在车间详情页面）
        updateWorkshopPageChips(increment);
        
        // 设置下一次更新
        chipAnimationData.animationTimer = setTimeout(updateChips, 2000);
    }
    
    updateChips();
}

// 更新工厂卡片中的生产芯数
function updateFactoryCardsChips(increment = 0) {
    const factoryCards = document.querySelectorAll('.factory-card');
    
    factoryCards.forEach((card, index) => {
        const factory = mockData.factories[index];
        if (factory) {
            const chipElement = card.querySelector('.factory-info-value');
            
            if (chipElement && chipElement.nextElementSibling?.textContent === '生产芯数') {
                const currentValue = parseInt(chipElement.textContent.replace(/,/g, '')) || 0;
                const targetValue = currentValue + increment;
                
                if (increment > 0) {
                    animateNumber(chipElement, currentValue, targetValue, 800);
                }
            }
        }
    });
}

// 更新车间详情页面的生产芯数
function updateWorkshopPageChips(increment = 0) {
    // 检查是否在车间详情页面
    const workshopDetail = document.getElementById('workshop-detail');
    if (workshopDetail && workshopDetail.style.display !== 'none') {
        // 更新质量状况中的总检测量
        const totalTestedElement = document.getElementById('total-tested');
        if (totalTestedElement && increment > 0) {
            const currentValue = parseInt(totalTestedElement.textContent.replace(/,/g, '')) || 0;
            const targetValue = currentValue + increment;
            animateNumber(totalTestedElement, currentValue, targetValue, 800);
        }
    }
}

// 停止生产芯数增长动画
function stopChipGrowthAnimation() {
    if (chipAnimationData.animationTimer) {
        clearTimeout(chipAnimationData.animationTimer);
        chipAnimationData.animationTimer = null;
    }
    chipAnimationData.isAnimating = false;
}

// 初始化页面
document.addEventListener('DOMContentLoaded', function() {
    initializeDashboard();
    startRealTimeUpdates();
});

// 初始化仪表板
function initializeDashboard() {
    updateDateTime();
    updateFactoryOverview();
    updateWorkshopDetail();
    startRealTimeUpdates();
    startChipGrowthAnimation();
}

// 更新日期时间
function updateDateTime() {
    const now = new Date();
    const timeElement = document.getElementById('current-time');
    const dateElement = document.getElementById('current-date');
    
    timeElement.textContent = now.toLocaleTimeString('zh-CN', { 
        hour12: false, 
        hour: '2-digit', 
        minute: '2-digit', 
        second: '2-digit' 
    });
    
    dateElement.textContent = now.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric', 
        weekday: 'long' 
    });
}





// 计算单个工厂的生产数据
function calculateFactoryMetrics(factoryId) {
    let totalChips = 0;
    let totalTested = 0;
    let totalDefective = 0;
    let totalOEE = 0;
    let activeLines = 0;
    
    // 获取该工厂的所有车间数据
    const factoryWorkshops = mockData.workshops[factoryId];
    if (factoryWorkshops) {
        Object.values(factoryWorkshops).forEach(workshop => {
            // 累计芯数（已发货订单）
            totalChips += workshop.orders.shipped || 0;
            
            // 累计质量数据
            if (workshop.quality) {
                totalTested += workshop.quality.totalTested || 0;
                totalDefective += workshop.quality.defectiveCount || 0;
            }
            
            // 累计生产线数据
            if (workshop.production && workshop.production.lines) {
                workshop.production.lines.forEach(line => {
                    if (line.status !== 'error') {
                        activeLines++;
                        totalOEE += line.oee || 0;
                    }
                });
            }
        });
    }
    
    // 计算良品率和平均OEE
    const yieldRate = totalTested > 0 ? ((totalTested - totalDefective) / totalTested * 100) : 0;
    const avgOEE = activeLines > 0 ? (totalOEE / activeLines) : 0;
    
    return {
        totalChips: totalChips,
        yieldRate: yieldRate,
        totalDefective: totalDefective,
        avgOEE: avgOEE
    };
}

// 更新工厂总览
function updateFactoryOverview() {
    // 更新总览统计
    const totalFactories = mockData.factories.length;
    const totalWorkshops = mockData.factories.reduce((sum, factory) => sum + factory.workshops, 0);
    const runningCount = mockData.factories.reduce((sum, factory) => sum + factory.runningWorkshops, 0);
    const warningCount = mockData.factories.filter(factory => factory.status === 'warning' || factory.status === 'error').length;
    
    document.getElementById('total-factories').textContent = totalFactories;
    document.getElementById('total-workshops').textContent = totalWorkshops;
    document.getElementById('running-count').textContent = runningCount;
    document.getElementById('warning-count').textContent = warningCount;
    
    // 更新工厂网格
    const factoryGrid = document.getElementById('factory-grid');
    factoryGrid.innerHTML = '';
    
    // 只显示前4个工厂（田字格布局）
    mockData.factories.slice(0, 4).forEach(factory => {
        // 计算该工厂的生产数据
        const metrics = calculateFactoryMetrics(factory.id);
        
        const factoryCard = document.createElement('div');
        factoryCard.className = `factory-card ${factory.status}`;
        factoryCard.onclick = () => showFactoryDetail(factory.id);
        
        factoryCard.innerHTML = `
            <div class="factory-header">
                <div class="factory-name">${factory.name}</div>
                <div class="factory-status ${factory.status}">${getStatusText(factory.status)}</div>
            </div>
            <div class="factory-info">
                <div class="factory-info-item">
                    <div class="factory-info-value">${metrics.totalChips.toLocaleString()}</div>
                    <div class="factory-info-label">生产芯数</div>
                </div>
                <div class="factory-info-item">
                    <div class="factory-info-value">${metrics.yieldRate.toFixed(2)}%</div>
                    <div class="factory-info-label">良品率</div>
                </div>
                <div class="factory-info-item">
                    <div class="factory-info-value">${factory.completedOrders}/${factory.totalOrders}</div>
                    <div class="factory-info-label">订单完成</div>
                </div>
                <div class="factory-info-item">
                    <div class="factory-info-value">${metrics.avgOEE.toFixed(2)}%</div>
                    <div class="factory-info-label">OEE</div>
                </div>
                <div class="factory-info-item">
                    <div class="factory-info-value">${factory.runningWorkshops}/${factory.workshops}</div>
                    <div class="factory-info-label">车间状态</div>
                </div>
                <div class="factory-info-item">
                    <div class="factory-info-value">${metrics.totalDefective}</div>
                    <div class="factory-info-label">不良品数</div>
                </div>
            </div>
        `;
        
        factoryGrid.appendChild(factoryCard);
    });
}

// 显示工厂详情
function showFactoryDetail(factoryId) {
    mockData.currentFactory = factoryId;
    mockData.currentWorkshop = Object.keys(mockData.workshops[factoryId])[0];
    
    updateWorkshopDetail();
    showWorkshopDetail();
}

// 初始化车间选择器
function initializeWorkshopSelector() {
    const workshopTabs = document.getElementById('workshop-tabs');
    workshopTabs.innerHTML = '';
    
    const workshops = Object.keys(mockData.workshops[mockData.currentFactory] || {});
    
    workshops.forEach(workshopName => {
        const tab = document.createElement('div');
        tab.className = `workshop-tab ${workshopName === mockData.currentWorkshop ? 'active' : ''}`;
        tab.textContent = workshopName;
        tab.onclick = () => selectWorkshop(workshopName);
        workshopTabs.appendChild(tab);
    });
}

// 选择车间
function selectWorkshop(workshopName) {
    mockData.currentWorkshop = workshopName;
    
    // 更新车间选择器状态
    const tabs = document.querySelectorAll('.workshop-tab');
    tabs.forEach(tab => {
        tab.classList.remove('active');
        if (tab.textContent === workshopName) {
            tab.classList.add('active');
        }
    });
    
    // 更新标题
    const factory = mockData.factories.find(f => f.id === mockData.currentFactory);
    document.getElementById('workshop-title').textContent = `${factory.name} - ${workshopName}`;
    
    updateWorkshopDetail();
}

// 显示车间详情
function showWorkshopDetail() {
    document.getElementById('factory-overview').style.display = 'none';
    document.getElementById('workshop-detail').style.display = 'block';
    
    const factory = mockData.factories.find(f => f.id === mockData.currentFactory);
    document.getElementById('workshop-title').textContent = `${factory.name} - ${mockData.currentWorkshop}`;
    
    // 初始化车间选择器
    initializeWorkshopSelector();
}

// 显示工厂总览
function showFactoryOverview() {
    document.getElementById('workshop-detail').style.display = 'none';
    document.getElementById('factory-overview').style.display = 'block';
}

// 更新车间详情
function updateWorkshopDetail() {
    const workshopData = mockData.workshops[mockData.currentFactory]?.[mockData.currentWorkshop];
    if (!workshopData) return;
    
    // 更新订单指标
    if (workshopData.orders) {
        document.getElementById('pending-orders').textContent = workshopData.orders.pending?.toLocaleString() || '0';
        document.getElementById('shipped-orders').textContent = workshopData.orders.shipped?.toLocaleString() || '0';
        document.getElementById('delayed-orders').textContent = workshopData.orders.delayed?.toLocaleString() || '0';
        
        if (workshopData.orders.progress) {
            renderOrderProgress(workshopData.orders.progress);
        }
    }
    
    // 更新生产指标
    if (workshopData.production) {
        updateProductionMetrics(workshopData.production);
    }
    
    // 更新质量指标
    if (workshopData.quality) {
        updateQualityMetrics(workshopData.quality);
    }
    
    // 更新事件列表
    if (workshopData.events) {
        updateEventList(workshopData.events);
    }
    
    // 更新不良品详情
    if (workshopData.quality?.defectDetails) {
        updateDefectDetails(workshopData.quality.defectDetails);
    }
    
    // 初始化图表
    if (workshopData.production) {
        initializeCharts(workshopData.production);
    }
}

// 渲染订单进度
function renderOrderProgress(progressData) {
    const progressList = document.getElementById('order-progress-list');
    progressList.innerHTML = '';
    
    if (!progressData) return;
    
    progressData.forEach(order => {
        const progressPercent = (order.actual / order.promised) * 100;
        const isDelayed = order.status === 'delayed';
        
        const progressItem = document.createElement('div');
        progressItem.className = `order-progress-item ${isDelayed ? 'delayed' : ''}`;
        
        progressItem.innerHTML = `
            <div class="order-info">
                <span class="order-id">${order.id}</span>
                <span class="order-status ${isDelayed ? 'delayed' : ''}">
                    ${isDelayed ? '预计延迟' : '正常进行'}
                </span>
            </div>
            <div class="progress-bar">
                <div class="progress-fill ${isDelayed ? 'delayed' : ''}" 
                     style="width: ${progressPercent}%"></div>
            </div>
            <div style="margin-top: 5px; font-size: 0.8rem; color: #8b9bb4;">
                承诺: ${order.promised} | 实际: ${order.actual} | 到期: ${order.dueDate}
            </div>
        `;
        
        progressList.appendChild(progressItem);
    });
}

// 更新生产指标
function updateProductionMetrics(productionData) {
    const linesContainer = document.getElementById('production-lines');
    linesContainer.innerHTML = '';
    
    if (!productionData?.lines) return;
    
    productionData.lines.forEach(line => {
        const lineElement = document.createElement('div');
        lineElement.className = `production-line ${line.status}`;
        lineElement.onclick = () => showLineDetails(line);
        
        lineElement.innerHTML = `
            <div class="line-number">${line.id}</div>
            <div class="oee-value">${line.oee.toFixed(2)}%</div>
        `;
        
        linesContainer.appendChild(lineElement);
    });
    
    // 更新平均OEE和产能达成率
    const avgOEE = productionData.lines.reduce((sum, line) => sum + line.oee, 0) / productionData.lines.length;
    const avgCapacity = productionData.lines.reduce((sum, line) => sum + line.capacity, 0) / productionData.lines.length;
    
    document.getElementById('avg-oee').textContent = `${avgOEE.toFixed(2)}%`;
    document.getElementById('capacity-rate').textContent = `${avgCapacity.toFixed(2)}%`;
}

// 显示生产线详情
function showLineDetails(line) {
    const message = `生产线 #${line.id}\n状态: ${getStatusText(line.status)}\nOEE: ${line.oee.toFixed(2)}%\n产能达成率: ${line.capacity.toFixed(2)}%`;
    alert(message);
}

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        'normal': '正常运行',
        'warning': '轻微异常',
        'error': '停机或严重异常'
    };
    return statusMap[status] || status;
}

// 更新质量指标
function updateQualityMetrics(qualityData) {
    if (!qualityData) return;
    
    document.getElementById('total-tested').textContent = qualityData.totalTested?.toLocaleString() || '0';
    document.getElementById('defective-count').textContent = qualityData.defectiveCount?.toLocaleString() || '0';
    document.getElementById('yield-rate').textContent = `${qualityData.yieldRate?.toFixed(2) || '0.00'}%`;
}

// 更新事件列表
function updateEventList(eventsData) {
    const eventList = document.getElementById('event-list');
    eventList.innerHTML = '';
    
    if (!eventsData) return;
    
    eventsData.forEach(event => {
        const eventItem = document.createElement('div');
        eventItem.className = `event-item ${event.type}`;
        
        const iconMap = {
            'error': 'fas fa-exclamation-circle',
            'warning': 'fas fa-exclamation-triangle',
            'success': 'fas fa-check-circle'
        };
        
        eventItem.innerHTML = `
            <i class="event-icon ${iconMap[event.type]}"></i>
            <div class="event-content">
                <div class="event-message">${event.message}</div>
                <div class="event-time">${event.time}</div>
            </div>
        `;
        
        eventList.appendChild(eventItem);
    });
}

// 更新不良品详情
function updateDefectDetails(defectDetailsData) {
    const defectDetails = document.getElementById('defect-details');
    defectDetails.innerHTML = '';
    
    if (!defectDetailsData) return;
    
    defectDetailsData.forEach(defect => {
        const defectItem = document.createElement('div');
        defectItem.className = 'defect-item';
        
        defectItem.innerHTML = `
            <div class="defect-info">
                <div class="defect-id">${defect.id}</div>
                <div class="defect-type">${defect.type}</div>
            </div>
            <div class="defect-batch">${defect.batch}</div>
        `;
        
        defectDetails.appendChild(defectItem);
    });
}

// 初始化图表
function initializeCharts(productionData) {
    if (!productionData) return;
    
    initializeCapacityChart(productionData.capacityTrend);
    initializeDefectChart();
}

// 初始化产能达成率趋势图
function initializeCapacityChart(capacityTrend) {
    const ctx = document.getElementById('capacity-chart').getContext('2d');
    
    // 销毁现有图表
    if (window.capacityChart) {
        window.capacityChart.destroy();
    }
    
    window.capacityChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月'],
            datasets: [{
                label: '产能达成率 (%)',
                data: capacityTrend?.map(v => parseFloat(v.toFixed(2))) || [],
                borderColor: '#4facfe',
                backgroundColor: 'rgba(79, 172, 254, 0.1)',
                borderWidth: 2,
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: false,
                    min: 85,
                    max: 100,
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    },
                    ticks: {
                        color: '#8b9bb4',
                        callback: function(value) {
                            return value.toFixed(2) + '%';
                        }
                    }
                },
                x: {
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    },
                    ticks: {
                        color: '#8b9bb4'
                    }
                }
            }
        }
    });
}

// 初始化不良品类型分布图
function initializeDefectChart() {
    const ctx = document.getElementById('defect-chart').getContext('2d');
    
    // 获取当前车间的质量数据
    const workshopData = mockData.workshops[mockData.currentFactory]?.[mockData.currentWorkshop];
    const defectTypes = workshopData?.quality?.defectTypes || [];
    
    // 销毁现有图表
    if (window.defectChart) {
        window.defectChart.destroy();
    }
    
    window.defectChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: defectTypes.map(d => d.type),
            datasets: [{
                data: defectTypes.map(d => d.count),
                backgroundColor: [
                    '#dc3545',
                    '#fd7e14',
                    '#ffc107',
                    '#20c997'
                ],
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        color: '#8b9bb4',
                        padding: 15,
                        usePointStyle: true
                    }
                }
            }
        }
    });
}

// 钻取功能 - 订单详情
function showOrderDrill(type) {
    const modal = document.getElementById('drill-modal');
    const title = document.getElementById('drill-title');
    const data = document.getElementById('drill-data');
    
    title.textContent = '订单详情';
    
    let content = '';
    
    switch(type) {
        case 'pending':
            content = `
                <div class="drill-section">
                    <h4>待发货订单详情</h4>
                    <p>当前待发货订单数量：<strong>${mockData.orders.pending}</strong></p>
                    <table class="drill-table">
                        <thead>
                            <tr>
                                <th>订单编号</th>
                                <th>客户名称</th>
                                <th>产品类型</th>
                                <th>数量</th>
                                <th>预计发货时间</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>ORD-101</td>
                                <td>客户A</td>
                                <td>产品X</td>
                                <td>500</td>
                                <td>2024-01-16</td>
                            </tr>
                            <tr>
                                <td>ORD-102</td>
                                <td>客户B</td>
                                <td>产品Y</td>
                                <td>300</td>
                                <td>2024-01-17</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            `;
            break;
        case 'delayed':
            content = `
                <div class="drill-section">
                    <h4>延迟订单详情</h4>
                    <p>当前延迟订单数量：<strong>${mockData.orders.delayed}</strong></p>
                    <table class="drill-table">
                        <thead>
                            <tr>
                                <th>订单编号</th>
                                <th>承诺完成量</th>
                                <th>实际完成量</th>
                                <th>完成率</th>
                                <th>预计延迟天数</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${mockData.orders.progress.filter(order => order.status === 'delayed').map(order => `
                                <tr>
                                    <td>${order.id}</td>
                                    <td>${order.promised}</td>
                                    <td>${order.actual}</td>
                                    <td>${((order.actual / order.promised) * 100).toFixed(2)}%</td>
                                    <td>3天</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `;
            break;
        case 'progress':
            content = `
                <div class="drill-section">
                    <h4>订单履约进度详情</h4>
                    <table class="drill-table">
                        <thead>
                            <tr>
                                <th>订单编号</th>
                                <th>承诺完成量</th>
                                <th>实际完成量</th>
                                <th>完成率</th>
                                <th>到期时间</th>
                                <th>状态</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${mockData.orders.progress.map(order => `
                                <tr>
                                    <td>${order.id}</td>
                                    <td>${order.promised}</td>
                                    <td>${order.actual}</td>
                                    <td>${((order.actual / order.promised) * 100).toFixed(2)}%</td>
                                    <td>${order.dueDate}</td>
                                    <td>${order.status === 'delayed' ? '延迟' : '正常'}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `;
            break;
    }
    
    data.innerHTML = content;
    modal.classList.add('active');
}

// 钻取功能 - 生产详情
function showProductionDrill(type) {
    const modal = document.getElementById('drill-modal');
    const title = document.getElementById('drill-title');
    const data = document.getElementById('drill-data');
    
    title.textContent = '生产详情';
    
    let content = '';
    
    switch(type) {
        case 'oee':
            content = `
                <div class="drill-section">
                    <h4>OEE详细数据</h4>
                    <table class="drill-table">
                        <thead>
                            <tr>
                                <th>生产线</th>
                                <th>OEE值</th>
                                <th>状态</th>
                                <th>时间开动率</th>
                                <th>性能开动率</th>
                                <th>合格品率</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${mockData.production.lines.map(line => `
                                <tr>
                                    <td>#${line.id}</td>
                                    <td>${line.oee.toFixed(2)}%</td>
                                    <td>${getStatusText(line.status)}</td>
                                    <td>${(line.oee * 0.95).toFixed(2)}%</td>
                                    <td>${(line.oee * 1.02).toFixed(2)}%</td>
                                    <td>${(line.oee * 1.03).toFixed(2)}%</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `;
            break;
        case 'capacity':
            content = `
                <div class="drill-section">
                    <h4>产能达成率详细数据</h4>
                    <table class="drill-table">
                        <thead>
                            <tr>
                                <th>生产线</th>
                                <th>计划产能</th>
                                <th>实际产能</th>
                                <th>达成率</th>
                                <th>状态</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${mockData.production.lines.map(line => `
                                <tr>
                                    <td>#${line.id}</td>
                                    <td>1000</td>
                                    <td>${Math.round(line.capacity * 10)}</td>
                                    <td>${line.capacity.toFixed(2)}%</td>
                                    <td>${getStatusText(line.status)}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `;
            break;
        case 'trend':
            content = `
                <div class="drill-section">
                    <h4>产能达成率趋势分析</h4>
                    <table class="drill-table">
                        <thead>
                            <tr>
                                <th>月份</th>
                                <th>产能达成率</th>
                                <th>环比变化</th>
                                <th>趋势</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${mockData.production.capacityTrend.map((rate, index) => {
                                const prevRate = index > 0 ? mockData.production.capacityTrend[index - 1] : rate;
                                const change = ((rate - prevRate) / prevRate * 100).toFixed(2);
                                const trend = change > 0 ? '上升' : change < 0 ? '下降' : '持平';
                                return `
                                    <tr>
                                        <td>${index + 1}月</td>
                                        <td>${rate.toFixed(2)}%</td>
                                        <td>${change}%</td>
                                        <td>${trend}</td>
                                    </tr>
                                `;
                            }).join('')}
                        </tbody>
                    </table>
                </div>
            `;
            break;
    }
    
    data.innerHTML = content;
    modal.classList.add('active');
}

// 钻取功能 - 质量详情
function showQualityDrill(type) {
    const modal = document.getElementById('drill-modal');
    const title = document.getElementById('drill-title');
    const data = document.getElementById('drill-data');
    
    title.textContent = '质量详情';
    
    let content = '';
    
    switch(type) {
        case 'overview':
            content = `
                <div class="drill-section">
                    <h4>质量检测总览</h4>
                    <p>总检测量：<strong>${mockData.quality.totalTested.toLocaleString()}</strong> 芯</p>
                    <p>不良品数：<strong>${mockData.quality.defectiveCount}</strong> 芯</p>
                    <p>良品率：<strong>${mockData.quality.yieldRate.toFixed(2)}%</strong></p>
                    <p>不良品率：<strong>${((mockData.quality.defectiveCount / mockData.quality.totalTested) * 100).toFixed(4)}%</strong></p>
                </div>
            `;
            break;
        case 'defects':
            content = `
                <div class="drill-section">
                    <h4>不良品详情</h4>
                    <table class="drill-table">
                        <thead>
                            <tr>
                                <th>不良品编号</th>
                                <th>类型</th>
                                <th>生产批次</th>
                                <th>检测时间</th>
                                <th>处理状态</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${mockData.quality.defectDetails.map(defect => `
                                <tr>
                                    <td>${defect.id}</td>
                                    <td>${defect.type}</td>
                                    <td>${defect.batch}</td>
                                    <td>${defect.time}</td>
                                    <td>已隔离</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `;
            break;
        case 'analysis':
            content = `
                <div class="drill-section">
                    <h4>不良品类型分析</h4>
                    <table class="drill-table">
                        <thead>
                            <tr>
                                <th>不良品类型</th>
                                <th>数量</th>
                                <th>占比</th>
                                <th>主要原因</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${mockData.quality.defectTypes.map(defect => `
                                <tr>
                                    <td>${defect.type}</td>
                                    <td>${defect.count}</td>
                                    <td>${defect.percentage}%</td>
                                    <td>设备参数偏差</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `;
            break;
    }
    
    data.innerHTML = content;
    modal.classList.add('active');
}

// 钻取功能 - 事件详情
function showEventDrill() {
    const modal = document.getElementById('drill-modal');
    const title = document.getElementById('drill-title');
    const data = document.getElementById('drill-data');
    
    title.textContent = '异常事件历史';
    
    const content = `
        <div class="drill-section">
            <h4>事件历史记录</h4>
            <table class="drill-table">
                <thead>
                    <tr>
                        <th>时间</th>
                        <th>事件类型</th>
                        <th>事件描述</th>
                        <th>影响范围</th>
                        <th>处理状态</th>
                    </tr>
                </thead>
                <tbody>
                    ${mockData.events.map(event => `
                        <tr>
                            <td>${event.time}</td>
                            <td>${getEventTypeText(event.type)}</td>
                            <td>${event.message}</td>
                            <td>生产线</td>
                            <td>${event.type === 'success' ? '已解决' : '处理中'}</td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
    `;
    
    data.innerHTML = content;
    modal.classList.add('active');
}

// 钻取功能 - 不良品详情
function showDefectDrill() {
    const modal = document.getElementById('drill-modal');
    const title = document.getElementById('drill-title');
    const data = document.getElementById('drill-data');
    
    title.textContent = '不良品完整记录';
    
    const content = `
        <div class="drill-section">
            <h4>不良品完整记录</h4>
            <table class="drill-table">
                <thead>
                    <tr>
                        <th>不良品编号</th>
                        <th>类型</th>
                        <th>生产批次</th>
                        <th>生产线</th>
                        <th>检测时间</th>
                        <th>处理状态</th>
                        <th>责任人</th>
                    </tr>
                </thead>
                <tbody>
                    ${mockData.quality.defectDetails.map(defect => `
                        <tr>
                            <td>${defect.id}</td>
                            <td>${defect.type}</td>
                            <td>${defect.batch}</td>
                            <td>#${Math.floor(Math.random() * 10) + 1}</td>
                            <td>${defect.time}</td>
                            <td>已隔离</td>
                            <td>质检员A</td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
    `;
    
    data.innerHTML = content;
    modal.classList.add('active');
}

// 关闭钻取弹窗
function closeDrillModal() {
    const modal = document.getElementById('drill-modal');
    modal.classList.remove('active');
}

// 获取事件类型文本
function getEventTypeText(type) {
    const typeMap = {
        'error': '错误',
        'warning': '警告',
        'success': '成功'
    };
    return typeMap[type] || type;
}

// 点击弹窗外部关闭
document.getElementById('drill-modal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeDrillModal();
    }
});

// 开始实时更新
function startRealTimeUpdates() {
    // 每秒更新时间
    setInterval(updateDateTime, 1000);
    
    // 每30秒更新数据
    setInterval(() => {
        updateMockData();
        updateFactoryOverview();
        updateWorkshopDetail();
    }, 30000);
    
    // 页面可见性变化时的处理
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            stopChipGrowthAnimation();
        } else {
            startChipGrowthAnimation();
        }
    });
}

// 更新模拟数据（模拟实时变化）
function updateMockData() {
    // 更新工厂数据
    mockData.factories.forEach(factory => {
        // 小幅波动OEE和产能
        factory.avgOEE += (Math.random() - 0.5) * 1;
        factory.avgOEE = Math.max(0, Math.min(100, factory.avgOEE));
        
        factory.avgCapacity += (Math.random() - 0.5) * 1;
        factory.avgCapacity = Math.max(0, Math.min(100, factory.avgCapacity));
        
        // 随机更新订单数据
        factory.completedOrders += Math.floor(Math.random() * 5);
        factory.totalOrders += Math.floor(Math.random() * 3);
    });
    
    // 更新车间数据
    Object.keys(mockData.workshops).forEach(factoryId => {
        Object.keys(mockData.workshops[factoryId]).forEach(workshopName => {
            const workshop = mockData.workshops[factoryId][workshopName];
            
            // 更新订单数据
            if (workshop.orders) {
                workshop.orders.pending += Math.floor(Math.random() * 10) - 5;
                workshop.orders.pending = Math.max(0, workshop.orders.pending);
                workshop.orders.shipped += Math.floor(Math.random() * 20);
            }
            
            // 更新生产线数据
            if (workshop.production?.lines) {
                workshop.production.lines.forEach(line => {
                    if (Math.random() < 0.1) { // 10%概率状态变化
                        const statuses = ['normal', 'warning', 'error'];
                        line.status = statuses[Math.floor(Math.random() * statuses.length)];
                    }
                    
                    // 小幅波动OEE和产能
                    line.oee += (Math.random() - 0.5) * 2;
                    line.oee = Math.max(0, Math.min(100, line.oee));
                    
                    line.capacity += (Math.random() - 0.5) * 2;
                    line.capacity = Math.max(0, Math.min(100, line.capacity));
                });
            }
            
            // 更新质量数据
            if (workshop.quality) {
                workshop.quality.totalTested += Math.floor(Math.random() * 100);
                workshop.quality.defectiveCount += Math.floor(Math.random() * 3);
                workshop.quality.yieldRate = ((workshop.quality.totalTested - workshop.quality.defectiveCount) / workshop.quality.totalTested * 100);
            }
            
            // 随机添加新事件
            if (Math.random() < 0.3) { // 30%概率添加新事件
                const eventTypes = ['success', 'warning', 'error'];
                const eventMessages = [
                    '生产线完成维护',
                    '新订单开始生产',
                    '质量检测通过',
                    '设备预防性维护',
                    '物料到货确认'
                ];
                
                const newEvent = {
                    type: eventTypes[Math.floor(Math.random() * eventTypes.length)],
                    message: eventMessages[Math.floor(Math.random() * eventMessages.length)],
                    time: new Date().toLocaleString('zh-CN')
                };
                
                if (!workshop.events) workshop.events = [];
                workshop.events.unshift(newEvent);
                if (workshop.events.length > 10) {
                    workshop.events.pop();
                }
            }
        });
    });
}

// 添加一些交互功能
document.addEventListener('click', function(e) {
    // 点击生产线时的交互
    if (e.target.closest('.production-line')) {
        const line = e.target.closest('.production-line');
        line.style.transform = 'scale(1.1)';
        setTimeout(() => {
            line.style.transform = 'scale(1)';
        }, 200);
    }
    
    // 点击事件项时的交互
    if (e.target.closest('.event-item')) {
        const eventItem = e.target.closest('.event-item');
        eventItem.style.background = 'rgba(255, 255, 255, 0.1)';
        setTimeout(() => {
            eventItem.style.background = '';
        }, 300);
    }
});

// 键盘快捷键
document.addEventListener('keydown', function(e) {
    switch(e.key) {
        case 'F5':
            e.preventDefault();
            location.reload();
            break;
        case 'Escape':
            closeDrillModal();
            break;
    }
});

// 页面可见性变化时的处理
document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        console.log('页面隐藏，暂停实时更新');
    } else {
        console.log('页面显示，恢复实时更新');
    }
});
